﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace N2.Details
{
	using System.ComponentModel;
	
	public class ContentItemTypeDescriptor
		: CustomTypeDescriptor
	{
		#region Constructors

		public ContentItemTypeDescriptor(
				ICustomTypeDescriptor parent,
				ContentItem contentItem)
			: base(parent)
		{
			this.instance = contentItem;
		}
		
		#endregion Constructors

		#region Fields

		protected readonly ContentItem instance;

		#endregion Fields

		public override string GetClassName()
		{
			return instance.GetType().Name;
		}

		public override PropertyDescriptorCollection GetProperties()
		{
			return this.GetProperties(new Attribute[0]);
		}

		public override PropertyDescriptorCollection GetProperties(Attribute[] attributes)
		{
			return
				new PropertyDescriptorCollection(
					TypeDescriptor
						.GetProperties(typeof(N2.ContentItem))
						.Cast<PropertyDescriptor>()
					.Concat(
						
						(
						from _detail in this.instance.Details
						select new { Key = "Details", Value = _detail.Value }
						).Concat(
							from _category in this.instance.DetailCollections
							from _property in _category.Value.Details
							select new { Key = _category.Key, Value = _property }
						).Select(_pair => new ContentItemPropertyDescriptor(
							TypeDescriptor.CreateProperty(
									typeof(ContentItem),
									_pair.Value.Name,
									typeof(string)),
								_pair.Value,
								_pair.Key)
						).Cast<PropertyDescriptor>()
					
					).ToArray());
		}
	}
}
